package com.chookss.mine.personal;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.video.entity.VideoEntity;
import com.chookss.video.recommend.VedioDetailActivity;
import com.chookss.view.MyRoundLayout;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

//更多课程
public class MyMoreLongVediosActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    private String courseCode = "", courseName = "";
    private MyLongVideoAdapter adapter;
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private List<VideoEntity> list = new ArrayList<>();
    private int  source=0; //0默认情况1学习任务过来的
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.common_srlview_center);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        courseCode = getIntent().getStringExtra("courseCode");
        courseName = getIntent().getStringExtra("courseName");
        source = getIntent().getIntExtra("source",0);
        commonTitleTxt.setText(courseName);
        if (Utils.isNull(courseName)) {
            commonTitleTxt.setText("更多课程");
        }
        ivNone.setBackgroundResource(R.drawable.icon_default_no_video);
        tvNone.setText("课程下下暂无数据");
        smrRf.setPadding(0, Utils.dip2px(this, 12), 0, 0);
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager1);
        recyclerView.setPadding(Utils.dip2px(this, 3), 0, Utils.dip2px(this, 3), 0);
        adapter = new MyLongVideoAdapter(R.layout.item_my_long_video, this, list);
        recyclerView.setAdapter(adapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("courseCode", courseCode);
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.selectCourseConnectVideo, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {

                JSONObject jsonObject = JSONObject.parseObject(data);
                loadEnd();
                if ("200".equals(jsonObject.getString("code"))) {
                    if(smrRf==null||llNone==null){
                        return;
                    }
                    String total = jsonObject.getString("total");
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    List<VideoEntity> VideoEntitys = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject userJson = jsonArray.getJSONObject(i);
                        VideoEntity videoEntity = JSON.toJavaObject(userJson, VideoEntity.class);
                        VideoEntitys.add(videoEntity);
                    }
                    if (currentPage == 1) {
                        list.clear();
                        adapter.notifyDataSetChanged();
                    }
                    int oldIndex = list.size();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("videoNum", total);
                    EventBus.getDefault().post(new MyEvent(map));
                    if (VideoEntitys != null && VideoEntitys.size() > 0) {
                        if (VideoEntitys.size() < pageSize) {
                            isEnd = true;
                        }
                        list.addAll(VideoEntitys);
                        adapter.notifyItemRangeChanged(oldIndex, VideoEntitys.size());
                        smrRf.setVisibility(View.VISIBLE);
                        llNone.setVisibility(View.GONE);
                    } else {
                        isEnd = true;
                        if (list.size() == 0) {
                            smrRf.setVisibility(View.GONE);
                            llNone.setVisibility(View.VISIBLE);
                        }
                    }
                }

            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
            }
        });
    }

    @OnClick({R.id.common_title_back})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
        }

    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    class MyLongVideoAdapter extends BaseQuickAdapter<VideoEntity, BaseViewHolderEx> {
        private Context context;
        private int width, height;

        public MyLongVideoAdapter(int layoutResId, Context context, @Nullable List<VideoEntity> data) {
            super(layoutResId, data);
            this.context = context;
            width = (Utils.getScreenWidthPixel(context) - Utils.dip2px(context, 42)) / 2;
            height = width * 110 / 183;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, VideoEntity item) {
            MyRoundLayout rl = helper.getView(R.id.item_rl);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) rl.getLayoutParams();
            params.height = height;
            rl.setLayoutParams(params);
            TextView tvTiltle = helper.getView(R.id.tvTiltle);
            TextView tvNumber = helper.getView(R.id.tvNumber);
            TextView tvTime = helper.getView(R.id.tvTime);
            ImageView ivBg = helper.getView(R.id.ivBg);
            tvTiltle.setText(item.videoTitle);
            tvTime.setText(Utils.changeTime(item.videoSeconds));
            tvNumber.setText(Utils.changeCounts(item.videoPlayCounts) + "次播放");
            GlideUtils.load(context, item.videoCoverPath, ivBg, R.drawable.default_vedio);
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, VedioDetailActivity.class);
                    intent.putExtra("video", item);
                    intent.putExtra("source", 1);
                    context.startActivity(intent);
                }
            });
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("videoId")) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).videoId.equals(map.get("videoId"))) {
                        if (map.containsKey("videoCollectCounts")) {
                            list.get(i).videoCollectCounts = map.get("videoCollectCounts");
                        }
                        if (map.containsKey("videoLikeCounts")) {
                            list.get(i).videoLikeCounts = map.get("videoLikeCounts");
                        }
                        if (map.containsKey("isCollect")) {
                            list.get(i).isCollect = map.get("isCollect");
                        }
                        if (map.containsKey("isLike")) {
                            list.get(i).videoLikeCounts = map.get("isLike");
                        }
                        if (map.containsKey("videoPlayCounts")) {
                            list.get(i).videoPlayCounts = map.get("videoPlayCounts");
                            list.get(i).isPlay = "1";
                            adapter.notifyItemChanged(i);
                        }
                    }
                }
            }
        }
    }
}
